package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectFeeQuery;
import com.ruoyi.project.mapper.ProjectAllocationMapper;
import com.ruoyi.project.mapper.ProjectFeeMapper;
import com.ruoyi.project.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class ProjectAllocationServiceImpl extends ServiceImpl<ProjectAllocationMapper, ProjectAllocation> implements IProjectAllocationService {
    @Resource
    private ProjectFeeMapper projectFeeMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IProjectParticipanService projectParticipanService;

    @Resource
    private IProjectGjpUserService projectGjpUserService;

    @Resource
    private IProjectService projectService;

    @Resource
    ISysDictDataService dictDataService;

    @Resource
    IProjectAllocationService allocationService;

    @Resource
    IProjectAllocationDetailService detailService;

    @Resource
    ProjectAllocationMapper allocationMapper;

    @Resource
    private IProjectAccountingService accountingService;

    @Override
    public void addAllocation(String projectNo) {
            //先获取项目提成
            //验收环节 还没有项目提成 设为0
            BigDecimal allCommission = BigDecimal.ZERO;
            //获取项目详细
            Project project = projectService.getById(projectNo);
            String housekeeperProject = project.getHousekeeperProject();
            String housekeeperName = project.getHousekeeperName();
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            //重新生成的时候先删除
            allocationService.deleteByProjectNo(projectNo,"1");
            allocationService.deleteByProjectNo(projectNo,"2");
            //1.保存绩效信息 根据项目id查询参与人员
            LambdaQueryWrapper<ProjectParticipan> wrapper = new QueryWrapper<ProjectParticipan>().lambda()
                    .eq(ProjectParticipan::getProjectNo, projectNo);
            List<ProjectParticipan> personList = projectParticipanService.list(wrapper);
            // 获取配置的字典值
            SysDictData dictData = new SysDictData();
            dictData.setDictType("range_type");
            List<SysDictData> dictDataList = dictDataService.selectDictDataList(dictData);
            // 遍历字典数据列表，检查是否存在匹配的 postId
            for (SysDictData d : dictDataList) {//循环设置的有哪些岗位有绩效
                ProjectAllocation allocation = new ProjectAllocation();
                allocation.setProjectNo(projectNo);
                //设置项目管家婆项目信息
                allocation.setHousekeeperProject(housekeeperProject);
                allocation.setHousekeeperName(housekeeperName);

                //设置标准岗位绩效系数
                Long ratio = Long.valueOf(d.getDictValue());
                allocation.setRatio(BigDecimal.valueOf(ratio));

                //设置标准岗位绩效金额 allCommission * ratio / 100
                BigDecimal performanceBonus = allCommission.multiply(new BigDecimal(ratio)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                System.out.println("绩效金额: " + performanceBonus);

                allocation.setMoney(performanceBonus);

                //设置岗位信息
                allocation.setPostId(Long.valueOf(d.getRemark()));
                allocation.setPostName(d.getDictLabel());

                //设置操作人
                allocation.setOperatorName(nickName);
                allocation.setOperatorId(SecurityUtils.getLoginUser().getUser().getUserId());
                allocation.setCurrent("1");
                //设置备注 项目经理给除了销售负责人之外的人打分 销售负责人给项目经理打分 5.17改 工程售前也属于销售负责人
                //标记
                if (allocation.getPostId().equals(2L) || allocation.getPostId().equals(13L)) {
                    allocation.setRemark("销售负责人");
                } else if (allocation.getPostId().equals(5L)) {
                    allocation.setRemark("总经理");
                } else {
                    allocation.setRemark("项目经理");
                }
//                allocation.setCurrent("1");
                //插入数据
                boolean save = allocationService.save(allocation);
                //插入成功 再保存明细信息  项目提成阶段
                if (save) {
                    // 假设这是总的绩效金
                    BigDecimal totalPerformanceMoney = allocation.getMoney(); // 请替换为实际获取总金额的方式
                    // 创建一个Map来存储每个岗位对应的人员列表，便于后续处理
                    Map<String, List<ProjectParticipan>> postIdToPersonsMap = new HashMap<>();
                    for (ProjectParticipan person : personList) {
                        // 将具有相同岗位ID的人员分组
                        String postId = String.valueOf(person.getPostId());
                        if (!postIdToPersonsMap.containsKey(postId)) {
                            postIdToPersonsMap.put(postId, new ArrayList<>());
                        }
                        postIdToPersonsMap.get(postId).add(person);
                    }

                    // 对于每个allocation对象，根据其岗位ID找到对应的所有人员，并分配绩效金额
                    for (ProjectParticipan person : personList) {
                        // 如果岗位id能匹配上(可能同一岗位有多个)
                        if (person.getPostId().equals(allocation.getPostId())) {
                            AllocationDetail allocationDetail = new AllocationDetail();

                            // 设置对应的项目id
                            allocationDetail.setProjectNo(projectNo);

                            // 设置父id
                            allocationDetail.setAllocationId(allocation.getId());

                            // 设置绩效系数 新增默认为100
                            allocationDetail.setRatio(new BigDecimal("100"));

                            // 获取该岗位下的所有人员数量
                            List<ProjectParticipan> personsInSamePost = postIdToPersonsMap.get(String.valueOf(person.getPostId()));
                            int numberOfPersons = personsInSamePost.size();

                            // 计算每个人的绩效金额
                            BigDecimal moneyPerPerson = totalPerformanceMoney.divide(new BigDecimal(numberOfPersons), 2, RoundingMode.HALF_UP);

                            // 设置绩效金额 总的
                            allocationDetail.setMoney(moneyPerPerson);

                            //设置个人绩效
                            String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
                            BigDecimal personAllocationMoney = moneyPerPerson.multiply(new BigDecimal(personAllocation));
                            allocationDetail.setPersonMoney(personAllocationMoney);

                            //设置部门绩效
                            String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
                            BigDecimal deptAllocationMoney = moneyPerPerson.multiply(new BigDecimal(deptAllocation));
                            allocationDetail.setDeptMoney(deptAllocationMoney);

                            // 设置参与人信息
                            allocationDetail.setPersonId(person.getParticipantId());
                            allocationDetail.setPersonName(person.getParticipanName());
                            allocationDetail.setCurrent("1");
                            allocationDetail.setStartDate(person.getUpdateTime());
                            // 保存到数据库
                            detailService.save(allocationDetail);
                        }
                    }

                    for (ProjectParticipan person : personList) {
                        // 如果岗位id能匹配上(可能同一岗位有多个)
                        if (person.getPostId().equals(allocation.getPostId())) {
                            AllocationDetail allocationDetail = new AllocationDetail();

                            // 设置对应的项目id
                            allocationDetail.setProjectNo(projectNo);

                            // 设置父id
                            allocationDetail.setAllocationId(allocation.getId());

                            // 设置绩效系数 新增默认为100
                            allocationDetail.setRatio(new BigDecimal("100"));

                            // 获取该岗位下的所有人员数量
                            List<ProjectParticipan> personsInSamePost = postIdToPersonsMap.get(String.valueOf(person.getPostId()));
                            int numberOfPersons = personsInSamePost.size();

                            // 计算每个人的绩效金额
                            BigDecimal moneyPerPerson = totalPerformanceMoney.divide(new BigDecimal(numberOfPersons), 2, RoundingMode.HALF_UP);

                            // 设置绩效金额
                            allocationDetail.setMoney(moneyPerPerson);

                            //设置个人绩效
                            String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
                            BigDecimal personAllocationMoney = moneyPerPerson.multiply(new BigDecimal(personAllocation));
                            allocationDetail.setPersonMoney(personAllocationMoney);

                            //设置部门绩效
                            String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
                            BigDecimal deptAllocationMoney = moneyPerPerson.multiply(new BigDecimal(deptAllocation));
                            allocationDetail.setDeptMoney(deptAllocationMoney);


                            // 设置参与人信息
                            allocationDetail.setPersonId(person.getParticipantId());
                            allocationDetail.setPersonName(person.getParticipanName());
                            allocationDetail.setCurrent("2");
                            allocationDetail.setStartDate(person.getUpdateTime());
                            // 保存到数据库
                            detailService.save(allocationDetail);
                        }
                    }
                }

            }
    }


    @Override
    public List<ProjectAllocation> getAllocationList(String projectNo,String current) {
        //重新查询所有信息  判断当前是销售负责人 还是项目经理 还是吴总 查询对应需要操作的

        //查询当前操作人有哪些权限
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ProjectParticipan> wrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(ProjectParticipan::getProjectNo, projectNo)
                .eq(ProjectParticipan::getParticipantId, userId);
        List<ProjectParticipan> personList = projectParticipanService.list(wrapper);

        Map<String, Boolean> allcationPermisson = getAllcationPermisson(projectNo);

        //销售负责人
        Boolean isSale = allcationPermisson.get("isSale");
        //项目经理
        Boolean isManager = allcationPermisson.get("isManager");
        //总经理 或 高级管理员
        Boolean all = allcationPermisson.get("all");

        LambdaQueryWrapper<ProjectAllocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectAllocation::getProjectNo, projectNo);
//        queryWrapper.eq(ProjectAllocation::getCurrent, current);
        List<ProjectAllocation> allocationList = allocationService.list(queryWrapper);

        List<ProjectAllocation> resultList = new ArrayList<>();

        for (ProjectAllocation allocation : allocationList) {
            Long id = allocation.getId();
            LambdaQueryWrapper<AllocationDetail> queryDetailWrapper = new LambdaQueryWrapper<>();
            queryDetailWrapper.eq(AllocationDetail::getAllocationId, id);
            queryDetailWrapper.eq(AllocationDetail::getCurrent, current);
            List<AllocationDetail> list = detailService.list(queryDetailWrapper);
            allocation.setDetailList(list);

            //如果是总经理或高级管理员
            if (all || isSale){
                resultList.add(allocation);
            } else if (isManager) {
                //如果是项目经理 只添加自己和自己管理的人 (意味着除了销售负责人)
                if (!allocation.getPostId().equals(5L)) {
                    resultList.add(allocation);
                }

            }else{
                //如果是普通用户  只看普通用户的 除去销售负责人和项目经理的

                if (!(allocation.getPostId().equals(5L) || allocation.getPostId().equals(2L))) {
                    resultList.add(allocation);
                }
            }

        }

        for (ProjectAllocation allocationDetail : resultList) {
            if ("销售负责人".equals(allocationDetail.getRemark())) {
                allocationDetail.setOper(isSale);
            }

            if ("项目经理".equals(allocationDetail.getRemark())) {
                allocationDetail.setOper(isManager);
            }

            if ("总经理".equals(allocationDetail.getRemark())) {
                allocationDetail.setOper(all);
            }

        }

        //设置 分配的权限 默认禁用  销售负责人给项目经理分配 项目经理给其他人分配 吴总可全部

        return resultList;
    }

    public Map<String, Boolean> getAllcationPermisson(String projectNo) {
        Map<String, Boolean> map = new HashMap<>();
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ProjectParticipan> wrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(ProjectParticipan::getProjectNo, projectNo)
                .eq(ProjectParticipan::getParticipantId, userId);
        List<ProjectParticipan> personList = projectParticipanService.list(wrapper);

        Boolean isSale = false;
        Boolean isManager = false;
        Boolean all = false;

        //如果是吴总或者高级管理员
        if (userId.equals(100L) || SecurityUtils.hasRole("gjadmin") || SecurityUtils.hasRole("admin")) {
            all = true;
            isSale = true;
            isManager = true;
        }

        for (ProjectParticipan person : personList) {
            //判断是否是销售负责人
            if (userId.equals(person.getParticipantId()) && person.getPostId().equals(5L)) {
                isSale = true;
            }

            if (userId.equals(person.getParticipantId()) && person.getPostId().equals(2L)) {
                isManager = true;
            }

        }

        map.put("isSale", isSale);
        map.put("isManager", isManager);
        map.put("all", all);

        return map;


    }

    @Override
    public void deleteByProjectNo(String projectNo,String current) {
        allocationMapper.deleteByProjectNo(projectNo,current);
        allocationMapper.deleteByProjectNoDetail(projectNo,current);
    }

}
